<?php

namespace app\common\model;

use app\common\service\FileService;

use app\helpers\Common;
use app\libs\traits\BaseModelTrait;

class File extends Base
{
    /**
     * Base Model Trait
     */
    use BaseModelTrait;

    // 当前模型名称 不带前缀
    protected $name = 'files';

    // 主键
    protected $pk = 'id';


    /**
     * 格式化列表数据
     */
    public static function formatDatas($list, $params = '')
    {
        foreach ($list as &$item) {
            $item = (new self())->formatItem($item, $params);
        }

        return $list;
    }

    /**
     * 格式化单个数据
     */
    public static function formatItem($item, $params = '')
    {
        if (!$item) {
            return '';
        }

        $item['full_file_url'] = full_file_url($item['file_url']);
        $item['file_size'] = FileService::sizeFormat($item['file_size']);

        return $item;
    }

    /**
     * 删除文件
     */
    public static function delFile($data)
    {
        // 删除文件
        $storage = $data['storage'];
        $file_url = $data['file_url'];
        if ($storage == 'local') {
            // 本地服务器
            $file_url = substr($file_url, stripos($file_url, config('path.upload_disk')));
            del_file($file_url);
            return ['code' => 1, 'msg' => ''];
        } elseif ($storage == 'qiniu') {
            // 七牛
            $qiniu = new \app\common\service\Qiniu();
            $key = substr($file_url, stripos($file_url, $qiniu->url));
            $result = $qiniu->delFile($key);
            return ['code' => 1, 'msg' => $result];
        } elseif ($storage == 'tencentyun') {
            // 腾讯云
            $qcloud = new \app\common\service\Qcloud();
            $key = substr($file_url, stripos($file_url, $qcloud->url));
            $result = $qcloud->delFile($key);
            return ['code' => 1, 'msg' => $result];
        }
    }
}
